<template>
  <div class="subsystemManage">
    <div class="header-search-box shadow">
      <sec-form
        :searchBox="{ span: 6 }"
        :span="6"
        :optionData="searchForm.optionData"
        :ruleForm="searchForm.data"
        :formData="searchForm.config"
        @reset="fatchData(true)"
        @submitForm="fatchData(true)"
      ></sec-form>
    </div>
    <div class="scene-main tab-scene-main">
      <div class="mul-btn">
        <!-- <el-button type="primary" @click="handleNew" icon="el-icon-plus">新建资产</el-button> -->
        <el-button type="primary" @click="handleReport" icon="el-icon-plus">资产上报</el-button>
        <el-button type="primary" @click="handleBatchOpt">批量操作</el-button>
        <el-button type="primary" @click="handleColumn" icon="el-icon-plus">设置列</el-button>
      </div>
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane :label="'全部'" :name="''"></el-tab-pane>
        <el-tab-pane
          v-for="(item, index) in $store.state.dictionary[100500]"
          :key="index"
          :label="item.label"
          :name="item.value.toString()"
        ></el-tab-pane>
      </el-tabs>
      <sec-table
        :loading="searchTable.loading"
        selection
        :tableData="searchTable.rows"
        :tableCol="searchTable.cols"
        ref="secTabel"
        @selectionChange="searchTableChoice"
      >
        <template v-slot:operation="{ data }">
          <el-tooltip placement="top" :disabled="data.row.canOperate == 1">
            <div slot="content">
              当前域名资产归属责任人中没有您，如需添加，请<strong style="color: #409eff">关注</strong>
            </div>
            <span style="margin: 0 5px">
              <el-button
                @click.native.prevent="handleViewDetail(data.row)"
                :disabled="data.row.canOperate == 0"
                type="text"
                >资产详情</el-button
              >
            </span>
          </el-tooltip>
          <el-tooltip placement="top" :disabled="data.row.canOperate == 1">
            <div slot="content">
              当前域名资产归属责任人中没有您，如需添加，请<strong style="color: #409eff">关注</strong>
            </div>
            <span style="margin: 0 5px">
              <el-button
                type="text"
                @click.native.prevent="evalDetail(data.row)"
                :disabled="data.row.canOperate == 0 || !data.row.reportId"
                >审计详情</el-button
              >
            </span>
          </el-tooltip>
          <el-tooltip placement="top" :disabled="data.row.canOperate == 1">
            <div slot="content">
              当前域名资产归属责任人中没有您，如需添加，请<strong style="color: #409eff">关注</strong>
            </div>
            <span style="margin: 0 5px">
              <el-button type="text" @click.native.prevent="handleOpt(data.row)" :disabled="data.row.canOperate == 0"
                >操作</el-button
              >
            </span>
          </el-tooltip>
          <el-tooltip placement="top" :disabled="data.row.canOperate == 1">
            <div slot="content">
              当前域名资产归属责任人中没有您，如需添加，请<strong style="color: #409eff">关注</strong>
            </div>
            <span style="margin: 0 5px">
              <el-button
                v-if="data.row.admin == 0"
                type="text"
                @click.native.prevent="handleEdit(data.row.id)"
                :disabled="data.row.canOperate == 0"
                >编辑</el-button
              >
            </span>
          </el-tooltip>
          <el-tooltip placement="top" :disabled="data.row.canOperate == 1">
            <div slot="content">
              当前域名资产归属责任人中没有您，如需添加，请<strong style="color: #409eff">关注</strong>
            </div>
            <span style="margin: 0 5px">
              <el-button type="text" @click.native.prevent="handleDelete(data.row)" :disabled="data.row.canOperate == 0"
                >删除</el-button
              >
            </span>
          </el-tooltip>
        </template>
      </sec-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        background
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :layout="layout"
        :total="totalSize"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="editData && Array.isArray(editData.ids) && editData.ids.length > 1 ? '批量操作' : '操作'"
      :visible.sync="opDialogVisible"
      width="50%"
    >
      <dialog-op v-if="opDialogVisible" :editData="editData" ref="opdialog"></dialog-op>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseOpDialog(false)">取 消</el-button>
        <el-button type="primary" @click="handleCloseOpDialog(true)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="设置列" :visible.sync="designColumnDialogVisible" width="50%">
      <sec-form
        ref="designCloumnDialogRef"
        :rules="designColumnDialog.rules"
        :ruleForm="designColumnDialog.ruleForm"
        :formData="designColumnDialog.formData"
        labelPosition="top"
      >
        <template v-slot:choiceColumnList>
          <div style="text-align: left"><b>已选择字段</b>（拖动可调整字段在列表中展示顺序）</div>
          <div style="text-align: left">
            <draggable v-model="designColumnDialog.ruleForm.columnName" group="“column”" @start="onStart" @end="onEnd">
              <el-tag
                v-for="item in designColumnDialog.ruleForm.columnName"
                style="margin: 0 5px; cursor: pointer; color: #454545"
                size="medium"
                :key="item.value"
                :closable="item.close"
                @close="selectColse(item)"
                type="warning"
                color="#fae0a1"
              >
                {{ item.label }}
              </el-tag>
            </draggable>
          </div>
          <br />
        </template>

        <template v-slot:columnList>
          <div style="text-align: left"><b>字段</b>（点击字段可以追加到"已选择字段"区域）</div>
          <div style="text-align: left">
            <el-tag
              v-for="item in designColumnDialog.ruleForm.notSelectName"
              style="margin: 0 7px; cursor: pointer"
              size="medium"
              :key="item.value"
              @click.native="noSelectClick(item)"
              type=""
              effect="dark"
            >
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </sec-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseColumnDialog(false)">取 消</el-button>
        <el-button type="primary" @click="handleCloseColumnDialog(true)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SecForm from "components/formValidate/myForm";
import SecTable from "components/table/comTable";
import { paginationMixin } from "common/js/mixin";
import dialogOp from "./propertyOpDialog";
import draggable from "vuedraggable";
import {
  allDomainApi,
  allLeaderApi,
  dynamicselectApi,
  assetsSubsystemCodeList,
  assetsSubsystemList,
  dynamicupdateApi,
  assetsSubsystemDelete,
} from "@/api/propertyManage";
export default {
  inject: ["reload"],
  name: "subsystemManage",
  mixins: [paginationMixin],
  components: {
    SecTable,
    SecForm,
    dialogOp,
    draggable,
  },
  data() {
    return {
      /**
       * 查询区域
       */
      searchForm: {
        /**
         * 查询表单数据
         */
        data: {
          domainList: [], // 域名
          assetCode: [], // appID
          leaderList: [], // 权属负责任
        },
        /**
         * 查询表单配置
         */
        config: [
          {
            type: "select",
            multiple: true,
            filterable: true,
            clearable: true,
            allowCreate: true,
            collapseTags: true,
            label: "域名",
            prop: "domainList",
          },
          {
            type: "select",
            multiple: true,
            filterable: true,
            clearable: true,
            allowCreate: true,
            collapseTags: true,
            label: "appID",
            prop: "assetCode",
          },
          {
            type: "select",
            collapseTags: true,
            clearable: true,
            multiple: true,
            filterable: true,
            label: "权属负责人",
            prop: "leaderList",
          },
        ],
        optionData: {
          domainList: [],
          assetCode: [],
          leaderList: [],
        },
      },
      disabledBatchOpt: false, //全部页签下，禁用批量操作按钮
      activeName: "",
      searchTable: {
        // 加载中
        loading: false,
        /***
         * 表格列
         */
        copycols: [],
        rows: [],
        cols: [
          {
            label: "资产ID",
            prop: "id",
            showOverflowTooltip: true,
          },
          {
            label: "appID",
            prop: "assetCode",
            showOverflowTooltip: true,
          },
          {
            label: "域名",
            prop: "domain",
            showOverflowTooltip: true,
          },
          {
            label: "资产状态",
            prop: "status",
            align: "center",
            width: 140,
            formatter: (row, column, cellValue, index) => {
              let ss = this.$store.state.dictionary[100500].filter((e) => e.value == cellValue);
              return Array.isArray(ss) && ss.length > 0 ? ss[0].label : "";
            },
          },
          {
            label: "系统名称",
            prop: "assetName",
            showOverflowTooltip: true,
          },
          {
            label: "权属负责人",
            prop: "leader",
            showOverflowTooltip: true,
          },
          {
            type: "link",
            label: "待处理风险",
            prop: "riskNum",
            showOverflowTooltip: false,
            linkConfig: {
              click: ({ row, column, $index }) => {
                //待处理：平台中风险状态为“整改中+待复核”
                let statuses = ["1-4", "5"]; //1-4整改中、5待复核
                this.utils.$router(
                  { path: "/control/risk", query: { statuses: JSON.stringify(statuses), assetCode: row.assetCode } },
                  "_blank",
                );
              },
            },
          },
          {
            type: "link",
            label: "已处理风险",
            prop: "riskDoneNum",
            showOverflowTooltip: false,
            linkConfig: {
              click: ({ row, column, $index }) => {
                //已处理：平台中风险状态为“已忽略+不修复+已修复”
                let statuses = ["8", "9", "11"]; //8不修复、9已修复、11 已忽略
                this.utils.$router(
                  { path: "/control/risk", query: { statuses: JSON.stringify(statuses), assetCode: row.assetCode } },
                  "_blank",
                );
              },
            },
          },
          {
            label: "达标状态",
            prop: "compliance",
            showOverflowTooltip: true,
          },
          {
            label: "信用分",
            prop: "creditScore",
            showOverflowTooltip: true,
          },
          {
            label: "录入时间",
            prop: "createTimeText",
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            fixed: "right",
            columnType: "slot",
            prop: "operation",
            width: 250,
          },
        ],
      },
      /**
       * 设置列弹窗区域
       */
      designColumnDialog: {
        id: "",
        columnClose: true,
        formData: [
          {
            type: "slot",
            // multiple: true,
            // filterable: true,
            label: "",
            prop: "choiceColumnList",
            // optionProps: { label: "tagName", value: "tagCode" },
          },
          {
            type: "slot",
            // multiple: true,
            // filterable: true,
            prop: "columnList",
            // optionProps: { label: "tagName", value: "tagCode" },
          },
        ],
        ruleForm: {
          focus: "",
          id: "",
          columnName: ["系统名称", "资产级别"],
          notSelectName: ["riskDoneNum", "riskDoneNum"],
        },
        rules: {
          focus: [{ required: true, message: "请输入", trigger: "blur" }],
        },
      },
      // 设置列弹窗
      designColumnDialogVisible: false,
      // 编辑时需要的数据
      editDataSelectIds: [],
      editData: {},
      //批量操作弹框
      opDialogVisible: false,
    };
  },
  async mounted() {
    this.activeName = sessionStorage.getItem("activeName") ? sessionStorage.getItem("activeName") : "";
    if (!this.activeName) {
      this.disabledBatchOpt = true;
    }
    this.searchTable.copycols = this.searchTable.cols;
    this.getSelectData();
    await this.fatchData();
    this.selectColumn();
  },
  methods: {
    //开始拖拽事件
    onStart(e) {
      this.drag = true;
    },
    //拖拽结束事件
    onEnd(e) {
      this.drag = false;
    },
    selectColse(item) {
      // 将原数组进行删除
      let index = this.designColumnDialog.ruleForm.columnName.indexOf(item);
      this.designColumnDialog.ruleForm.columnName.splice(index, 1);
      //添加到上面数组中
      this.designColumnDialog.ruleForm.notSelectName.push(item);
    },
    noSelectClick(item) {
      // 将原数组进行删除
      let index = this.designColumnDialog.ruleForm.notSelectName.indexOf(item);
      this.designColumnDialog.ruleForm.notSelectName.splice(index, 1);
      // 添加到上面数组中
      this.designColumnDialog.ruleForm.columnName.push(item);
    },
    async handleCloseOpDialog(isSubmit) {
      if (isSubmit) {
        //需要提交数据
        let res = await this.$refs.opdialog.submit();
        if (!res) return;
        if (res.code == 0) {
          this.opDialogVisible = false;
          this.fatchData();
        }
        //如果是资产打标处理
        if (res.sign == "tag") {
          this.message.success({ message: `成功${res.data}条` });
        } else {
          let { succNums, failNums } = res.data;
          if (failNums == "0") {
            this.message.success({ message: `成功${succNums}条，失败${failNums}条` });
          } else {
            this.message.info({ message: `成功${succNums}条，失败${failNums}条` });
          }
        }
      } else {
        this.opDialogVisible = false;
      }
      return false;
    },
    // 获取下拉框数据
    getSelectData() {
      // 获取权属负责人
      allLeaderApi({ assetType: "SSO" }).then((res) => {
        this.searchForm.optionData.leaderList = res.data.map((item) => {
          return { label: item.name + "--" + item.account, value: item.account };
        });
      });
      // 获取域名
      allDomainApi({ assetType: "SSO" }).then((res) => {
        this.searchForm.optionData.domainList = res.data.map((item) => {
          return { label: item, value: item };
        });
      });
      // 获取appID
      assetsSubsystemCodeList({ assetType: "SSO" }).then((res) => {
        this.searchForm.optionData.assetCode = res.data.map((item) => {
          return { label: item, value: item };
        });
      });
    },
    fatchData(paginationReset) {
      // 解决点击搜索或者重置的时候 改成第一页
      if (paginationReset) {
        this.paginationReset();
      }
      this.searchTable.loading = true;
      let data = Object.assign(this.searchForm.data);
      assetsSubsystemList({
        pageNum: this.page,
        pageSize: this.pageSize,
        ...data,
        assetType: "SSO",
        status: this.activeName === "0" ? "" : this.activeName,
      })
        .then((res) => {
          this.searchTable.loading = false;
          this.searchTable.rows = res.data;
          this.totalSize = res.count;
        })
        .catch(() => {
          this.searchTable.loading = false;
        });
    },
    // table 多选选中
    searchTableChoice(e) {
      let t = this.searchTable.cols.findIndex((v) => v.label == "资产状态");

      if (!e.name) {
        this.disabledBatchOpt = true;
        if (t == -1) {
          this.searchTable.cols.splice(1, 0, {
            label: "资产状态",
            prop: "status",
            align: "center",
            formatter: (row, column, cellValue, index) => {
              let ss = this.$store.state.dictionary[100500].filter((e) => e.value == cellValue);
              return Array.isArray(ss) && ss.length > 0 ? ss[0].label : "";
            },
          });
        }
      } else {
        if (t != -1) {
          this.searchTable.cols.splice(t, 1);
        }
        this.disabledBatchOpt = false;
      }
      this.editDataSelectIds = e.map((e) => {
        return e.id;
      });
    },
    // 编辑
    handleEdit(id) {
      this.$router.push({
        path: "/property/subsystem/edit",
        query: { id },
      });
    },
    handleReport() {
      this.$router.push({
        path: "/property/subsystem/edit",
        query: {},
      });
    },
    handleOpt(row) {
      this.editData.ids = [row.id];
      this.editData.status = row.status;
      this.editData.editTagFlag = row.editTagFlag;
      this.opDialogVisible = true;
    },
    evalDetail(row) {
      console.log(row);
      this.$router.push({
        path: "/evaluate/manage/special/detail",
        query: {
          id: row.reportId,
          assetId: row.id,
          assetCode: row.assetCode,
        },
      });
    },
    // 批量操作
    handleBatchOpt() {
      this.editData.ids = this.editDataSelectIds;
      if (this.editDataSelectIds.length == 1) {
        let findItem = this.searchTable.rows.find((item) => item.id == this.editDataSelectIds[0]);
        this.editData["editTagFlag"] = findItem?.editTagFlag;
      }

      if (this.editData.ids && Array.isArray(this.editData.ids) && this.editData.ids.length > 0) {
        this.opDialogVisible = true;
        this.editData.status = this.activeName;
      } else {
        this.message.warning({ message: "请选择资产后操作" });
      }
    },
    handleDelete(row) {
      this.$confirm("此操作不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        assetsSubsystemDelete({ id: row.id }).then(async (res) => {
          let state = this.message.state(res);
          if (!state) return;
          await this.fatchData();
        });
      });
    },
    handleColumn() {
      this.designColumnDialogVisible = true;
    },
    async tabClick(e) {
      sessionStorage.setItem("activeName", e.name);
      this.searchForm.data.status = e.name;
      await this.fatchData();
    },
    // 执行搜索列
    selectColumn() {
      dynamicselectApi({ assetType: "SSO" }).then((res) => {
        this.designColumnDialog.id = res.data.id;
        // 渲染已经选择的列
        var columnNameTemp = [];
        res.data.columnName.forEach((element) => {
          let index = this.$store.state.dictionary["subsystemColumn"].findIndex((item, index) => {
            return item.value === element;
          });
          if (index !== -1) {
            columnNameTemp.push(this.$store.state.dictionary["subsystemColumn"][index]);
          }
        });
        this.designColumnDialog.ruleForm.columnName = columnNameTemp;
        // 渲染未选择的列
        var notSelectNameTemp = [];
        res.data.notSelectName.forEach((element) => {
          let index = this.$store.state.dictionary["subsystemColumn"].findIndex((item, index) => {
            return item.value === element;
          });
          if (index != -1) {
            notSelectNameTemp.push(this.$store.state.dictionary["subsystemColumn"][index]);
          }
        });

        this.designColumnDialog.ruleForm.notSelectName = notSelectNameTemp;

        // 控制表格中的显示
        var cols = [];
        // 取出操作

        var operation = this.searchTable.copycols[this.searchTable.copycols.length - 1];

        this.designColumnDialog.ruleForm.columnName.forEach((element) => {
          let index = this.searchTable.copycols.findIndex((item) => {
            return item.prop === element.value;
          });
          if (index != -1) {
            cols.push(this.searchTable.copycols[index]);
          }
        });
        cols.push(operation);
        this.searchTable.cols = cols;
      });
    },
    //执行更新列
    updateColumn() {
      let columnName = this.designColumnDialog.ruleForm.columnName.map((item) => {
        return item.value;
      });
      dynamicupdateApi({
        id: this.designColumnDialog.id,
        columnName: columnName,
        assetType: "SSO",
      }).then((res) => {
        let state = this.message.state(res);
        if (!state) {
          return;
        }
        this.selectColumn();
      });
    },
    handleViewDetail(row) {
      this.$router.push({
        path: "/property/subsystem/manage/detail",
        query: {
          id: row.id,
        },
      });
    },

    async handleSizeChange(e) {
      this.pageSize = e;
      await this.fatchData();
    },
    // 当前页改变
    async handleCurrentChange(e) {
      this.page = e;
      await this.fatchData();
    },
    handleCloseColumnDialog(isSubmit) {
      if (isSubmit) {
        this.updateColumn();
        this.reload();
        this.designColumnDialogVisible = false;
      } else {
        this.designColumnDialogVisible = false;
      }
    },
  },
};
</script>

<style scoped></style>
